package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/shirou/gopsutil/v3/mem"
	"go-proxy/admin/vo"
	"go-proxy/common"
	"go-proxy/proxy"
	"sync/atomic"
)

func GetOverView(c *gin.Context) {
	var result vo.OverViewVO
	// 获取当前代理服务数量
	result.ProxyNum = proxy.GetRunningServerNum()
	memoryInfo, err := getMemoryInfo()
	if err != nil {
		vo.BizError(c, "获取内存信息失败")
		return
	}
	result.Memory = memoryInfo
	result.ActiveNum = atomic.LoadInt64(&proxy.ActiveConnectionsNum)
	result.RequestNum = atomic.LoadInt64(&proxy.ServerRequestNum)
	vo.OKData(c, result)
}

// getMemoryInfo 获取内存信息
func getMemoryInfo() (vo.MemoryVO, error) {
	var memory vo.MemoryVO
	v, err := mem.VirtualMemory()
	if err != nil {
		common.LogErrorf("Error getting memory info:%v", err)
		return memory, err
	}

	// 打印内存使用情况
	totalUnit, totalValue := formatMemory(v.Total)
	freeUnit, freeValue := formatMemory(v.Free)
	usedUnit, usedValue := formatMemory(v.Used)

	memory.Total = fmt.Sprintf("%.2f%s", totalValue, totalUnit)
	memory.Free = fmt.Sprintf("%.2f%s", freeValue, freeUnit)
	memory.Used = fmt.Sprintf("%.2f%s", usedValue, usedUnit)
	memory.Rate = int(v.UsedPercent)

	return memory, nil
}

// formatMemory 根据内存大小返回合适的单位和值
func formatMemory(bytes uint64) (string, float64) {
	const (
		KB = 1024
		MB = KB * 1024
		GB = MB * 1024
	)

	if bytes >= GB {
		return "G", float64(bytes) / float64(GB)
	} else if bytes >= MB {
		return "M", float64(bytes) / float64(MB)
	} else {
		return "K", float64(bytes) / float64(KB)
	}
}
